<?php

/**
* Ticket Controller
*/
class TicketsController extends AppController
{
	var $name = 'Tickets';
	var $components = array('UserAuth', 'RequestHandler', 'ContentRight', 'Email');
	var $uses = array('Ticket', 'Batch', 'User', 'Receiptbook', 'Project', 'Milestone', 'Role');
	var $helpers = array ('ajax', 'Time', 'Format', 'Number');

	public function beforeFilter()
	{
		if ($this->RequestHandler->isAjax()) {
	        $db =& ConnectionManager::getDataSource('default');
	        $db->fullDebug = false;
	    } else {
			$this->set('project_id', $this->params['projectId']);
			$this->set('project_name', $this->params['projectName']);
		}
	}
	
	/**
	 * Home page of tickets.
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	function index()
	{
		$project_id = $this->params['projectId'];
		$tickets = array();
		if ($project_id != null) {
			$this->UserAuth->checkPermission($project_id);
			$this->Ticket->unbindModel(array('hasMany' => array('Reply', 'Document', 'Funding'), 'belongsTo' => array('Milestone')));			$tickets = $this->Ticket->findAllByProjectIdAndDrafted($project_id, 0, null, 'status');
			$this->set ('tickets', $tickets);
			$this->set ('allowDelete' ,$this->UserAuth->checkAcces($this->params['projectId'], 'project_ticket_delete'));
		}
	}
	
	/**
	 * function used to show advance filter form in ajax.
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	function homeAvc() {
		$this->render('homeAvc', 'ajax');
	}
	
	/**
	 * function used to show normal filter form in ajax.
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	function home() {
		$this->render('home', 'ajax');
	}
	
	/**
	 * Show the a Ticket from a ticket_id, if the ticket isn't qualify, redirection to the qualify action.
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	function view($ticket_id) {
		$project_id = $this->params['projectId'];
		$project_name = $this->params['projectName'];
		if ($ticket_id) {
			$disable = false;
			$this->Ticket->id = $ticket_id;
			$ticket = $this->Ticket->read();
			//print_r($ticket);
			if ($ticket == null) {
				$this->Session->setFlash('This ticket doesn\'t existe.');
				$this->redirect('/' . $project_name . '/'. $project_id . '/tickets/');
			}
			if ($ticket['Ticket']['status'] == 'to qualify') {
				$this->redirect('/' . $project_name . '/'. $project_id . '/tickets/qualify/'. $ticket_id);
			}
			for ($i = 0; $i < count($ticket['Reply']); $i++) {
				$this->User->unbindModel(array('belongsTo' => array('Company')));
				$this->User->unbindModel(array('hasMany' => array('Role')));
				$user = $this->User->findById($ticket['Reply'][$i]['user_id']);
				$ticket['Reply'][$i]['User'] = $user['User'];	
			}
			$this->data = $ticket;
			$authorized = false;
			if ($ticket['Ticket']['status'] == 'closed') {
				$disable = true;
				$authorized = true;
			}
			$user = $this->Session->read('User');
			$status_id = 0;
			foreach ($user['Role'] as $role) {
				if ($role['project_id'] == $project_id) {
					$status_id = $role['status_id'];
					break;
				}
			}
			if (!$disable && $status_id > 3) {
				$disable = true;
				// The user is not a smile user so he's not authorized to reopen a Ticket
				$authorized = false;
			}
			$this->set ('allowDelete' ,$this->UserAuth->checkAcces($this->params['projectId'], 'project_ticket_delete'));
			$this->Project->recursive = '0';
			$company = $this->Project->findById ($this->params['projectId']);
			$cond = array(
					'company_id' => $company['Company']['id'],
					'project_id' => $project_id
					);
			$Receiptbook = $this->Receiptbook->generateList($cond, null,null, '{n}.Receiptbook.id', '{n}.Receiptbook.name');
			$this->set('Receiptbook', $Receiptbook);
			$this->set('batches', $this->Batch->generateList(
				array('project_id' => $this->params['projectId'], 'finished' => 0), null, null, '{n}.Batch.id', '{n}.Batch.name'));
			$this->set('Milestones',$this->Batch->Milestone->generateList(
				array('batch_id' => $ticket['Ticket']['batch_id']), null, null, '{n}.Milestone.id', '{n}.Milestone.name'));				
			$cond = array(
					'project_id' => $this->params['projectId'],
					'status_id' => array('1', '2', '3', '4'));
			$smile_user = $this->Role->findall($cond);
			$this->set('smileUsr', $smile_user);
			$this->set('ticket', $ticket);
			$this->set('allow_crud', !$disable);
			$this->set('qualif_detail', true);
			$this->set('authorized', $authorized);
			
			$this->set ('allowDeleteDoc' ,$this->UserAuth->checkAcces($this->params['projectId'], 'project_document_del'));
			$user = $this->UserAuth->getUser();
			$this->set ('user_id' ,$user['id']);
		}
   	}

	/**
	 * Add a new Ticket, first creation of the draft of the ticket, a cron will delete unused draft.
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	function add() {
		// Check if the user can qualify the ticket.
		$allow_qualify = $this->UserAuth->checkAcces($this->params['projectId'], 'project_ticket_qualify');
		$this->Project->recursive = '0';
		$company = $this->Project->findById ($this->params['projectId']);
		$cond = array(
				'company_id' => $company['Project']['company_id'],
				'project_id' => $this->params['projectId']
				);
		$Receiptbook = $this->Receiptbook->generateList($cond, null,null, '{n}.Receiptbook.id', '{n}.Receiptbook.name');
		$this->set('Receiptbook', $Receiptbook);
		$cond = array(
				'project_id' => $this->params['projectId'],
				'status_id' => array('1', '2', '3', '4'));
		$smile_user = $this->Role->findall($cond);
		$this->set('smileUsr', $smile_user);
		$this->set('batches', $this->Batch->generateList(
			array('project_id' => $this->params['projectId'], 'finished' => 0), null, null, '{n}.Batch.id', '{n}.Batch.name'));
		$this->set('Milestones',$this->Batch->Milestone->generateList(
			array('batch_id' => 0), null, null, '{n}.Milestone.id', '{n}.Milestone.name'));

		$this->Milestone->unbindModel(array('belongsTo' => array('Batch')));
		$milestones = $this->Milestone->findAllByBatchId(0);
		$this->set('default_milestones', $milestones);
		if (empty($this->data)) {
			$ticket = array('Ticket' => 
						array(	'drafted' => 1,
							  	'status' => 'to qualify',
								'creation_date' => date("Y-m-d H:i:s"),
								'project_id' => $this->params['projectId'],
								'user_id' => $this->UserAuth->user['User']['id']));
			if ($this->Ticket->save($ticket['Ticket'])) {
				$ticket_drafted_id = $this->Ticket->getLastInsertId();
				$ticket['Ticket']['id'] = $ticket_drafted_id;
				$ticket['Funding'] = array();
				$this->set('ticket_id', $ticket_drafted_id);
			}			
			$this->set ('allow_qualify', $allow_qualify);
			$this->set ('allow_crud', $allow_qualify);
			$this->set ('qualif_detail', $allow_qualify);
			$this->set('ticket', $ticket);
			
			$this->render();
		} else {
			$this->data['Ticket']['drafted'] = 0;
			$this->data['Ticket']['creation_date'] = date("Y-m-d H:i:s");
			$this->data['Ticket']['update_date'] = date("Y-m-d H:i:s");
			$this->cleanUpFields('Ticket');
			$ticket = $this->data;
			//print_r($this->data);
			$this->data = $this->ticketToBatch($this->data, $ticket);
			if ($this->Ticket->save($this->data)) {
				//ok cool, the stuff is valid
				$this->Session->setFlash('The ticket has been added.');
				$this->sendMail($this->params['projectName'], $this->params['projectId'], $this->data, $allow_qualify);
				if ($this->data['Ticket']['add_doc'])
					$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/tickets/qualify/' . $this->data['Ticket']['id']);
				else
					$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/projects/');
			} else {
				$this->set('disable', false);
				$this->set('errorMessage', 'Please correct errors below.');
				$this->set('ticket_id', $this->data['Ticket']['id']);
				$this->render();
			}
		}
	}
	
	
	private function ticketToBatch($data, $ticket) {
		if (isset($data['Batch'])) {
			if ($data['Batch']['create'] == 1) {
				$batch = array('name' => $ticket['Ticket']['name'],
							'description' => $ticket['Ticket']['description'],
							'project_id' => $this->params['projectId']);
				$milestones = $data['Milestone'];
				// Batch success insert
				if ($this->Batch->save($batch)) {
					$batch_id  = $this->Batch->getLastInsertId();
					$data['Ticket']['batch_id'] = $batch_id;
					for($i = 0; !empty($milestones[$i]); $i++) {
						if ($milestones['check_' . $i] == 0) {
							continue;
						}
						$this->Milestone->id = $milestones[$i];
						$milestone_src = $this->Milestone->read();
						$milestone = array('id'=> 'NULL',
											'name' => $milestone_src['Milestone']['name'],
											'batch_id' => $batch_id,
											'deadline' => $milestones['deadline_'.$i.'_year']
											.'-'.$milestones['deadline_'.$i.'_month']
											.'-'.$milestones['deadline_'.$i.'_day']);
						$this->Milestone->save($milestone);
					}
				}
			}
		}
		return $data;
	}
	
	/**
	 * Function use to qualify each ticket submit by the client.
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	public function qualify($ticket_id)
	{
		// Droit pour qualifier le ticket.
		$allow_qualify = $this->UserAuth->checkAcces($this->params['projectId'], 'project_ticket_qualify');
		if (empty($this->data) == false) {
			$id = $this->data['Ticket']['id'];
			$this->Ticket->id = $id;
			$ticket = $this->Ticket->read();
			$allow_crud = ($ticket['User']['id'] == $this->UserAuth->user['User']['id']);
			$this->data['Ticket']['update_date'] = date("Y-m-d H:i:s");
			if ($allow_qualify) {
				$this->data['Ticket']['status'] = 'in process';
				$this->data = $this->ticketToBatch($this->data, $ticket);
			}
			$this->cleanUpFields('Ticket');
			if ($allow_crud || $allow_qualify) {
				$this->Ticket->save($this->data);
				if (isset($this->data['UserTicket'])) {
					$ticket['UserTicket'] = $this->data['UserTicket'];
				}
				$this->data['Ticket']['creation_date'] = $ticket['Ticket']['creation_date'];
				$this->data['Ticket']['user_id'] = $ticket['Ticket']['user_id'];
				$this->qualifyMail($this->params['projectName'], $this->params['projectId'], $this->data);
			}
			if ($allow_qualify) {
				$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/tickets/view/' . $id);
			} else {
				$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/tickets/qualify/' . $id);
			}
		} else {
			$this->Ticket->id = $ticket_id;
			$ticket = $this->Ticket->read();
			$allow_crud = ($ticket['User']['id'] == $this->UserAuth->user['User']['id']);
			// if Ticket is already qualify redirect to view
			if ($ticket['Ticket']['status'] != 'to qualify') {
				$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/tickets/view/' . $ticket['Ticket']['id']);
				return;
			}
			$batches = $this->Batch->findAllByProjectIdAndFinished($this->params['projectId'], 0);
			$batches = $this->createBatchArray($batches);
			$this->Project->recursive = '0';
			$company = $this->Project->findById ($this->params['projectId']);
			$cond = array(
					'company_id' => $company['Project']['company_id'],
					'project_id' => $this->params['projectId']
					);
			$Receiptbook = $this->Receiptbook->generateList($cond, null,null, '{n}.Receiptbook.id', '{n}.Receiptbook.name');
			$this->set('Receiptbook', $Receiptbook);
			$cond = array(
					'project_id' => $this->params['projectId'],
					'status_id' => array('1', '2', '3', '4'));
			$smile_user = $this->Role->findall($cond);
			$this->set('smileUsr', $smile_user);
			$this->set('batches', $batches);
			$this->set('ticket', $ticket);
			
			// The user can edit and delete his own tickets. In all other cases he can't do nothing.
			$this->set ('allow_crud', $allow_crud);
			if ($allow_qualify) {
				$this->set ('allow_crud', true);
			}

			$this->set('qualif_detail', $allow_qualify);
			$this->Milestone->unbindModel(array('belongsTo' => array('Batch')));
			$milestones = $this->Milestone->findAllByBatchId(0);
			$this->set('default_milestones', $milestones);
			$this->data = $ticket;
			$this->set ('allowDeleteDoc' ,$this->UserAuth->checkAcces($this->params['projectId'], 'project_document_del'));
			$user = $this->UserAuth->getUser();
			$this->set ('user_id' ,$user['id']);
		}
	}
	
	/**
	 * Update information of a ticket then return to the ticket
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	public function update() {
		if (empty($this->data) == false) {
			$this->data['Ticket']['update_date'] = date("Y-m-d H:i:s");
			$this->cleanUpFields('Ticket');
			$changelog = $this->compare($this->data);
			if ($this->UserAuth->checkAcces($this->params['projectId'], 'project_ticket_reply_status')) {
				$this->data['Ticket']['status'] = 'idle';
			}
			if ($changelog != "") {
				$this->data['Reply']['response'] .= " ";
			}
			if ($this->data['Ticket']['status'] == 'closed') {
				// count the number of non-closed ticket and if the number is equal to 0, close the batch.
				$cond = array('status' => '<> closed', 'Ticket.batch_id' => $this->data['Ticket']['batch_id']);
				$count = $this->Ticket->findCount($cond);
				if ($count == 1) {
					// we close the batch
					$batch = array('Batch' => array('id' => $this->data['Ticket']['batch_id'], 'finished' => '1'));
					$this->Batch->save($batch);
				}
			}
			$this->Ticket->save($this->data);
			$this->data['Reply']['date'] = date("Y-m-d H:i:s");
			$this->data['Reply']['changelog'] = $changelog;
			$this->Ticket->Reply->save($this->data);
			$this->replyMail($this->params['projectName'],$this->params['projectId'], $this->data);
			$this->Session->setFlash('Ticket Updated');
			$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId']
					. '/tickets/view/'. $this->data['Ticket']['id']);
		}
	}
	
	/**
	 * Reopen a ticket already closed.
	 *
	 * @return void
	 * @author Rémi Peron
	 */
	public function reopen() {
		if (empty($this->data) == false) {
			$this->data['Ticket']['update_date'] = date("Y-m-d H:i:s");
			$this->cleanUpFields('Ticket');
			$this->data['Ticket']['status'] = 'idle';
			$user = $this->UserAuth->getUser();
			
			$reply = array('Reply' => array (
				'date' => date("Y-m-d H:i:s"),
				'changelog' => "Ticket status change from closed to idle<br/>",
				'response' => " ",
				'user_id' => $user['id'],
				'ticket_id' => $this->data['Ticket']['id']));
			$this->Ticket->save($this->data);
			$this->Ticket->Reply->save($reply['Reply']);
			$this->Session->setFlash(__('Ticket Re-open', true));
			$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId']
					. '/tickets/view/'. $this->data['Ticket']['id']);
		}
	}
	
	
	/**
	 * Create a well formated Array for batches
	 *
	 * @return array well formated for batches
	 * @author Rémi Peron
	 **/
	private function createBatchArray($batches = null)
	{
		if ($batches == null)
			return null;
		$res[0] = 'Sélectionner un lot';
		foreach ($batches as $key => $batch) {
			$res[$batch['Batch']['id']] = $batch['Batch']['name'];
		}
		return $res;
	}
	
	/**
	 * Create the changelog, for update function.
	 *
	 * @return String 
	 * @author Rémi Peron
	 **/
	private	function compare ($data = null) 
	{
		$changelog = "";
		if ($data == null) {
			return $changelog;
		}
		$this->Ticket->id = $data['Ticket']['id'];
		$ticket = $this->Ticket->read();
		if (isset($data['Ticket']['status']) && $ticket['Ticket']['status'] != $data['Ticket']['status']) {
			if ($data['Ticket']['status'] == 'to qualify') {
				$changelog.="Ticket status change from ".$ticket['Ticket']['status'] . " to qualify <br/>";
			} else {
				$changelog.="Ticket status change from ".$ticket['Ticket']['status'] . " to " . $data['Ticket']['status']. "<br/>";
			}
		}

		if (isset($data['Ticket']['kind']) && $ticket['Ticket']['kind'] != $data['Ticket']['kind']) {
		$changelog .= "Ticket kind change from " . $ticket['Ticket']['kind'] . " to " . $data['Ticket']['kind'] . "<br/>";
		}
		if (isset($data['Ticket']['severity']) && $ticket['Ticket']['severity'] != $data['Ticket']['severity']) {
		$changelog.="Ticket severity change from ".$ticket['Ticket']['severity']." to ".$data['Ticket']['severity']."<br/>";
		}
		return $changelog;
	}
	
	/**
	 * Ajax filter
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	public function filter($project_id)
	{
		$this->Project->recursive = '-1';
		$project = $this->Project->findById($project_id);
		$this->set ('project_id' , $project_id);
		$this->set ('project_name', $project['Project']['rewrite_name']);
		
		if (isset($this->data)) {
			$this->Ticket->unbindModel(array('hasMany' => array('Reply', 'Document', 'Funding'), 'belongsTo' => array('Milestone')));
			if (is_numeric($ticket_id = $this->data['Ticket']['id'])) {
				$tickets = $this->Ticket->findAllByProjectIdAndDraftedAndId($project_id, 0, $ticket_id, null, 'status');
			} else {
				if ($this->data['Ticket']['name'] != '') {
					$keyword = $this->data['Ticket']['name'];
					$cond = array(
						'Ticket.project_id' => $project_id,
						'drafted' => 0,
						'or' => array
						(
							'Ticket.name' => 'LIKE %' . $keyword . '%',
							'Ticket.description' => 'LIKE %' . $keyword . '%'
						)
						);
					$tickets = $this->Ticket->findAll($cond, null, 'status');
				} else {
					$tickets = $this->Ticket->findAllByProjectIdAndDrafted($project_id, 0, null, 'status');
				}
			}
			$this->set ('tickets', $tickets);
			$this->set ('allowDelete' ,$this->UserAuth->checkAcces($project_id, 'project_ticket_delete'));
		}
		$this->render('filter', 'ajax');
	}
	
	
	/**
	 * Closed a ticket
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	public function delete($ticket_id = null) {
		if ($ticket_id == null) {
			$this->Session->setFlash('Ticket doesn\'t existe');
			$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/tickets/');
		}
		if ($this->UserAuth->checkAcces($this->params['projectId'], 'project_ticket_delete')
			|| !$this->UserAuth->checkAcces($this->params['projectId'], 'project_ticket_qualify')) {
				$this->Ticket->id = $ticket_id;
				$this->Ticket->unbindModel(
					array(
						'belongsTo' => array('Milestone', 'Batch'),
						'hasMany' => array('Reply', 'Document', 'Funding'),
						'hasAndBelongsToMany' => array('UserTicket')));
				$ticket = $this->Ticket->read();
				// if ($ticket['User']['id'] != $this->UserAuth->user['User']['id'] || ) {
				// 	$this->Session->setFlash('You can only delete your own ticket');
				// } else {
					$ticket['Ticket']['status'] = 'closed';
					if ($this->Ticket->save($ticket)) {
						$this->Session->setFlash('Ticket closed');
						// count the number of non-closed ticket and if the number is equal to 0, close the batch.
						$cond = array('status' => '<> closed', 'Ticket.batch_id' => $this->data['Ticket']['batch_id']);
						$count = $this->Ticket->findCount($cond);
						if ($count == 1) {
							// we close the batch
							$batch = array('Batch' => array('id' => $this->data['Ticket']['batch_id'], 'finished' => '1'));
							$this->Batch->save($batch);
						}
					} else {
						$this->Session->setFlash('Unable to close this ticket');
					}
				// }
			} else {
				$this->Session->setFlash('You are not authorized to close a ticket');
			}
			$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/tickets/');
		}
		
		/**
		 * Send mail when CP qualify a ticket
		 *
		 * @return void
		 * @author Rémi Peron
		 **/
		private function qualifyMail($project_name, $project_id, $ticket) {
			$this->User->id = $ticket['Ticket']['user_id'];
			$this->User->unbindModel(array('belongsTo' => array('Company'),'hasMany' => array('Role')));
			$user = $this->User->read();
			$urlPath = Router::getPaths();

			$this->set('base', $urlPath['base']);
			$this->set('full_base_url', FULL_BASE_URL);
			$this->set ('project_name', $project_name);
			$this->set ('ticket', $ticket);
			$this->set ('project_id', $project_id);
			$this->set ('user', $user);
			
			$affect_user = array();
			if (isset($ticket['UserTicket'])) {
				foreach ($ticket['UserTicket']['UserTicket'] as $user_ticket) {
					$this->Role->recursive = '0';
					$this->Role->unbindModel(array('belongsTo' => array('Project')));
					$user = $this->Role->findByUserIdAndProjectId($user_ticket, $project_id);
					$affect_user[] = $user;
				}
			}
			$this->set ('affect_user', $affect_user);
			
			$this->Role->unbindModel(array('belongsTo'=> array('Project')));
			$role = $this->Role->findallByProjectId($project_id);
			foreach ($role as $user) {
				if ($user['User']['mail'] == '') {
					continue;
				}
				$send = true;
				if ($user['Role']['status_id'] == 2 || $user['Role']['status_id'] == 5) {
					$send = false;
					foreach ($affect_user as $userAffected) {
						if ($user['User']['id'] == $userAffected['User']['id']) {
							$send = true;
							break;
						}
					}
				}
				if ($send) {
					$this->Email->to = $user['User']['mail'];
					$this->Email->subject = 'Re: [WebExchange][' . $project_name .'][' . $ticket['Ticket']['id']. '] ' .  $ticket['Ticket']['name']; 
			        $this->Email->replyTo = 'noreply@smile.fr'; 
			        $this->Email->from = 'Smile WebExchange <webExchange@smile.fr>'; 
					$this->Email->template = 'qualify';
					$this->Email->sendAs = 'html';
					$this->Email->charset = 'utf-8';
					$this->Email->send();
					$this->Email->reset();
				}
			}
		}

		/**
		 * Send mail when Someone reply to a ticket
		 *
		 * @return void
		 * @author Rémi Peron
		 **/		
		private function replyMail($project_name, $project_id, $ticket) {
			$this->User->id = $ticket['Ticket']['user_id'];
			$this->User->unbindModel(array('belongsTo' => array('Company'),'hasMany' => array('Role')));
			$user = $this->User->read();
			$urlPath = Router::getPaths();

			$this->Ticket->Reply->unbindModel(array('belongsTo'=> array('Ticket')));
			$replies = $this->Ticket->Reply->findAllByTicketId($ticket['Ticket']['id'], null, 'date DESC');

			$this->Ticket->recursive = '-1';
			$this->Ticket->id = $ticket['Ticket']['id'];
			$ticket = $this->Ticket->read();

			$this->set('base', $urlPath['base']);
			$this->set('full_base_url', FULL_BASE_URL);
			$this->set ('project_name', $project_name);
			$this->set ('ticket', $ticket);
			$this->set ('project_id', $project_id);
			$this->set ('user', $user);
			$this->set ('replies', $replies);
			
			$affect_user = array();
			if (isset($ticket['UserTicket'])) {
				foreach ($ticket['UserTicket']['UserTicket'] as $user_ticket) {
					$this->Role->recursive = '0';
					$this->Role->unbindModel(array('belongsTo' => array('Project')));
					$user = $this->Role->findByUserIdAndProjectId($user_ticket, $project_id);
					$affect_user[] = $user;
				}
			}
			$this->set ('affect_user', $affect_user);
			
			$this->Role->unbindModel(array('belongsTo'=> array('Project')));
			$role = $this->Role->findallByProjectId($project_id);
			foreach ($role as $user) {
				if ($user['User']['mail'] == '') {
					continue;
				}
				$send = true;
				if ($user['Role']['status_id'] == 2 || $user['Role']['status_id'] == 5) {
					$send = false;
					foreach ($affect_user as $userAffected) {
						if ($user['User']['id'] == $userAffected['User']['id']) {
							$send = true;
							break;
						}
					}
				}
				if ($send) {
					$this->Email->to = $user['User']['mail'];
					$this->Email->subject = 'Re: [WebExchange][' . $project_name .'][' . $ticket['Ticket']['id']. '] ' .  $ticket['Ticket']['name']; 
			        $this->Email->replyTo = 'noreply@smile.fr'; 
			        $this->Email->from = 'Smile WebExchange <webExchange@smile.fr>'; 
					$this->Email->template = 'reply';
					$this->Email->sendAs = 'html';
					$this->Email->charset = 'utf-8';
					$this->Email->send();
					$this->Email->reset();
				}
			}
			
		}

		/**
		 * Send mail when someone add a ticket
		 *
		 * @return void
		 * @author Rémi Peron
		 **/		
	    private function sendMail($project_name, $project_id, $ticket, $allow_qualify = false) { 
			$this->User->id = $ticket['Ticket']['user_id'];
			$this->User->unbindModel(array('belongsTo' => array('Company'),'hasMany' => array('Role')));
			$user = $this->User->read();
			$urlPath = Router::getPaths();

			$this->set('base', $urlPath['base']);
			$this->set('full_base_url', FULL_BASE_URL);
			$this->set ('project_name', $project_name);
			$this->set ('ticket', $ticket);
			$this->set ('project_id', $project_id);
			$this->set ('user', $user);
			$this->set ('adv', false);
			$affect_user = array();			
			if ($allow_qualify) {
				if (isset($ticket['UserTicket'])) {
					foreach ($ticket['UserTicket']['UserTicket'] as $user_ticket) {
						$this->Role->recursive = '0';
						$this->Role->unbindModel(array('belongsTo' => array('Project')));
						$user = $this->Role->findByUserIdAndProjectId($user_ticket, $project_id);
						$affect_user[] = $user;
						$this->set ('adv', true);
					}
				}				
			}
			$this->set ('affect_user', $affect_user);
		
			$this->Role->unbindModel(array('belongsTo'=> array('Project')));
			$role = $this->Role->findallByProjectId($project_id);
			foreach ($role as $user) {
				if ($user['User']['mail'] == '') {
					continue;
				}
				$this->Email->to = $user['User']['mail'];
				$this->Email->subject = '[WebExchange][' . $project_name .'][' . $ticket['Ticket']['id']. '] ' .  $ticket['Ticket']['name']; 
		        $this->Email->replyTo = 'noreply@smile.fr'; 
		        $this->Email->from = 'Smile WebExchange <webExchange@smile.fr>'; 
				$this->Email->template = 'ticket';
				$this->Email->sendAs = 'html';
				$this->Email->charset = 'utf-8';
				$this->Email->send();
				$this->Email->reset();
			}
	    }
}

?>